package com.example.dataservice.serviceimpl;

import com.example.dataservice.mapper.ImageMapper;
import com.mysql.cj.result.Field;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboService;
import org.example.api.service.ImageService;
import org.example.api.model.Image;

import java.io.File;

/**
 * @description: TODO
 * @author: uu
 * @data: 2023/7/25 下午 07:52
 * @version: v1.0
 */
@DubboService(interfaceClass = ImageService.class, version = "1.0")
public class ImageImpl implements ImageService {
    @Resource
    private ImageMapper imageMapper;

    @Override
    /*将uid、图片的path存到数据库中*/
    public int userImage(Image image) {
        int count = 0;
        // 查询用户是否有图片
        Image target = imageMapper.selectImageByUid(image);
        if (target == null){
            count = imageMapper.insertImage(image);
            if (count < 1){
                throw new RuntimeException("头像上传数据库失败");
            }
        }else {
            // 将原来的文件删除
            File file = new File(target.getPath());
            if (file.exists()) {
                file.delete();
            }
            count = imageMapper.updateImage(image);
            if (count < 1){
                throw new RuntimeException("头像更新失败");
            }
        }
        // no : insert
            // yes: update
        return count;
    }

    @Override
    /*查询用户图片地址*/
    public Image queryUserImage(Integer uid) {
        Image image = null;
        if (uid != null && uid > 0){
            image = new Image();
            image.setUid(uid);
            image = imageMapper.selectImageByUid(image);
        }
        return image;
    }
}
